/*
 * data_thread.h
 *
 *  Created on: 30.06.2013
 *      Author: SpirTanol
 */

#ifndef DATA_THREAD_H_
#define DATA_THREAD_H_

// QT
#include <QThread>

class DeviceInfo;
class ModbusPort;
class DataPacket;
class DataEvent;
class ConfigPacket;
class WatchDataPacket;
class RunConfigPacket;
class RunConfigProgressPacket;
class CrashOscillogramPacket;
class ProtocolPacket;
class CrashProtocolPacket;

class DataThread : public QThread
{
	Q_OBJECT

	DeviceInfo *oDevInfo;

	ModbusPort *oMPort;
	short oPassword;

	WatchDataPacket *oData; /**< Данные */
	ProtocolPacket *oEventProtocol;
	CrashProtocolPacket *oCrashProtocol;

	ConfigPacket *oConfigPacket;
	ConfigPacket *oConfigPacketWrite;
	bool oNeedConfig;

	bool oConnection;

	uint oTime;
	bool oWriteTime;

	bool oResetCrashProtocol;
	bool oResetWorkProtocol;
	bool oResetWorkTime;

	bool oChangeAppenOut;

	int oCommandEngine;

	RunConfigPacket *oRunConfig;
	RunConfigProgressPacket* oRunConfigProgress;
	bool oRunAutoConfig;

	CrashOscillogramPacket *oOscillogramPacket;

public:
	DataThread(const DeviceInfo *dev);
	~DataThread();

	inline int password() const { return int(oPassword); }
	inline void setPassword(int password) { oPassword = short(password); }

	void openConnect();
	void closeConnect();

	inline bool isConnected() const { return oConnection; }

	inline void readConfig() { oNeedConfig = true; }

	inline const DeviceInfo *device() const { return oDevInfo; }

	inline void writeConfig(ConfigPacket *writeConfig) { oConfigPacketWrite = writeConfig; }

	inline void writeTime(uint time) { oTime = time; oWriteTime = true; }

	inline void resetCrahProtocol() { oResetCrashProtocol = true; }
	inline void resetWorkProtocol() { oResetWorkProtocol = true; }
	inline void resetWorkTime() { oResetWorkTime = true; }

	inline void changeAppendOut() { oChangeAppenOut = true; }

	inline void commandEngine(int command) { oCommandEngine = command; }

	inline void runAutoConfig() { oRunAutoConfig = true; }

	inline const WatchDataPacket *watchPacket() const { return oData; }
	inline const ConfigPacket *configPacket() const { return oConfigPacket; }

private:
	void run(); // [virtual]

	bool readPacket(DataPacket *packet);
	/** Записывает пакет данных в устройство, если reqPass = true, то перед каждой порцией данных пакета, пишется пароль */
	bool writePacket(DataPacket *packet, bool reqPass = false);

private slots:
	void stoped();
	void connectionClosed();

signals:
	void dataEvent(const DataEvent *e);

};

#endif /* DATA_THREAD_H_ */
